<template>
    <div class="chart" ref="leftCenterChart"></div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue';
import * as echarts from 'echarts';
import { getLeftCenterChartData } from '@/api/data-screen/LeftChart';

onMounted(() => {
    initLeftCenterChart(); // 左中间
})

//颜色工具函数，修改16进制透明度
function hexToRgba(hex, alpha = 1) {
    // 移除输入字符串中的 '#' 号
    let r, g, b;

    if (hex.length === 4) {
        r = parseInt(hex[1] + hex[1], 16);
        g = parseInt(hex[2] + hex[2], 16);
        b = parseInt(hex[3] + hex[3], 16);
    } else {
        r = parseInt(hex.slice(1, 3), 16);
        g = parseInt(hex.slice(3, 5), 16);
        b = parseInt(hex.slice(5, 7), 16);
    }

    if (alpha >= 0 && alpha <= 1) {
        return `rgba(${r}, ${g}, ${b}, ${alpha})`;
    } else {
        return `rgb(${r}, ${g}, ${b})`;
    }
}

//左中间图
const leftCenterChart = ref<HTMLElement | null>(null);
// 初始化
let leftCenterChartInstance: echarts.ECharts | null = null;
const initLeftCenterChart = () => {
    if (leftCenterChart.value) {
        leftCenterChartInstance = echarts.init(leftCenterChart.value);
        updateLeftCenterChart();
    }
};

// 获取根元素字体大小
const rootFontSize = parseFloat(getComputedStyle(document.documentElement).fontSize);

// 定义一个函数，将 rem 转换为像素值
function remToPx(rem) {
    return rem * rootFontSize;
}

const ages = [18, 19, 20, 21, 22, 23, 24, 25, 26];
const initData = async () => {
    try {
        return await getLeftCenterChartData(ages);
    } catch {
        console.log("获取左中图数据失败！")
    }
}

// 更新数据
const updateLeftCenterChart = async () => {
    try {

        const result = await initData();
        const preReserveCount = result.data.preReserveCount;
        const clubCount = result.data.clubCount;


        type EChartsOption = echarts.EChartsOption;
        var option: EChartsOption;

        // 固定配色方案
        const colors = ['#FFA726', '#18FFFF']; // 橙黄 + 青蓝

        option = {
            color: colors,
            
            tooltip: {
                trigger: 'axis',
                axisPointer: {
                    type: 'cross',
                    label: {
                        backgroundColor: '#6a7985'
                    }
                },
                textStyle: {  // 新增文字单位转换
                    fontSize: '0.75rem'  // 12px → 0.75rem
                }
            },
            legend: {
                data: ['预储', '军事兴趣类社团'],
                textStyle: {
                    color: '#FFF',
                    fontSize: '1rem'
                },
                itemWidth: 20,  // 保持数值不变（无单位）
                itemHeight: 10,
                itemGap: 8
            },
            
            grid: {
                top: '11%',
                left: '0%',
                right: '4%',
                bottom: '12%',
                containLabel: true,
                //borderColor: 'rgba(176,208,255,0.2)' // 网格线颜色
            },
            //backgroundColor: '#0A235C', // 深蓝背景色
            // textStyle: {
            //     color: '#B0D0FF' // 文本颜色为浅蓝
            // },

            xAxis: [
                {
                    type: 'category',
                    //name: '年龄/岁',
                    axisLabel: {
                        formatter: '{value}岁',
                        fontSize: '0.75rem'
                    },
                    //nameLocation:'end',
                    //nameGap:-1,
                    boundaryGap: false,
                    data: ages,
                    axisLine: {
                        lineStyle: {
                            color: '#ccc',
                        }
                    },
                }
            ],
            yAxis: [
                {
                    type: 'value',
                    name: '人数/人',
                    nameTextStyle: {
                        fontSize: '0.75rem'  // 12px → 0.75rem
                    },
                    axisLabel: {
                        fontSize: '0.75rem'  // 12px → 0.75rem
                    },
                    //max: 600, // 调整最大值为独立显示后的数据范围
                    //y轴
                    axisLine: {
                        //show:true,
                        lineStyle: {
                            color: '#ccc'
                        }
                    },
                }
            ],
            series: [

                {
                    name: '军事兴趣类社团',
                    type: 'line',
                    smooth: true,
                    lineStyle: {
                        width: remToPx(0.3),
                        color: colors[0],
                    },
                    showSymbol: true,
                    symbol: 'circle',  // 增加符号形状
                    symbolSize: remToPx(0.45),     // 调大符号尺寸
                    itemStyle: {
                        color: colors[0],
                        borderColor: '#FFF',  // 符号描边
                        borderWidth: remToPx(0.1)
                    },
                    areaStyle: {
                        color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                            { offset: 0, color: hexToRgba(colors[0], 0.8) }, // 2条折线起始透明度 
                            { offset: 1, color: hexToRgba(colors[0], 0.2) }  // 2条折线结束透明度 
                        ])
                    },
                    emphasis: {
                        focus: 'series'
                    },
                    data: clubCount
                },
                {
                    name: '预储',
                    type: 'line',
                    smooth: true,
                    lineStyle: {
                        width: remToPx(0.2),
                        color: colors[1],
                    },
                    showSymbol: true,
                    symbol: 'circle',
                    symbolSize: remToPx(0.45),
                    itemStyle: {
                        color: colors[1],
                        borderColor: '#FFF',
                        borderWidth: remToPx(0.1)
                    },
                    areaStyle: {
                        color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                            { offset: 0, color: hexToRgba(colors[1], 0.6) },
                            { offset: 1, color: hexToRgba(colors[1], 0.1) }
                        ])
                    },
                    emphasis: {
                        focus: 'series'
                    },
                    data: preReserveCount
                }
            ]
        };

        option && leftCenterChartInstance.setOption(option);

    } catch (error) {
        console.error("获取左中图数据失败:", error);
    }
};

</script>

<style scoped>
.chart {
    height: 100%;
    width: 100%;
}
</style>